<?php

namespace Dgyun\IpHelper\Ip2Region;


use Dgyun\IpHelper\Arr;
use Dgyun\IpHelper\Ip2Region\Data\Ip2Region;

class Ip2RegionHelper
{

    protected $ip2region;

    function __construct()
    {
        $this->ip2region = new Ip2Region(dirname(__FILE__) . '/Data/ip2region.db');
    }


    public function searchIp2Region($ip)
    {
        try {
            $data = $this->ip2region->btreeSearch(trim($ip));
            $data = explode('|', Arr::get($data, 'region'));
            return [
                'code'     => 1,
                'message'  => 'ok',
                'ip'       => $ip,
                'state'    => Arr::get($data, 0),
                'province' => Arr::get($data, 2),
                'city'     => Arr::get($data, 3),
                'from'     => Arr::get($data, 4),
            ];

        } catch (\Exception $e) {
            return [
                'code'     => 2,
                'message'  => $e->getMessage(),
                'ip'       => $ip,
                'state'    => '',
                'province' => '',
                'city'     => '',
                'from'     => '',
            ];
        }

    }


}